import { get as storeGet } from 'svelte/store';
import { userStore } from '../stores/userStore';

export const apiUrl = import.meta.env.VITE_API_URL || '';

function getToken() {
    return storeGet(userStore).token;
}

export async function request(method: string, endpoint: string, data: any) {
    const token = getToken();

    try {
        const response = await fetch(`${apiUrl}${endpoint}`, {
            method: method,
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        });

        if (!response.ok) {
            if (response.status == 401) {
                userStore.update(store => {
                    return {
                      ...store,
                      isLoggedIn: false,
                      id: 0,
                      token: '',
                    };
                  });
            }
            
            throw new Error(`Error: ${response.status}`);
        }

        return await response.json();
    } catch (error) {
        console.error('Error in request:', error);
        throw error;
    }
}
export async function get(endpoint: string, data: any) {
    const token = getToken();

    try {
        const queryParams = new URLSearchParams(data).toString();
        const response = await fetch(`${apiUrl}${endpoint}?${queryParams}`, {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            }
        });

        if (!response.ok) {
            if (response.status == 401) {
                userStore.update(store => {
                    return {
                      ...store,
                      isLoggedIn: false,
                      id: 0,
                      token: '',
                    };
                  });
            }
            throw new Error(`Error: ${response.status}`);
        }

        return await response.json();
    } catch (error) {
        console.error('Error in get request:', error);
        throw error;
    }
}
export async function getWithHeaders(endpoint: string, data: any) {
    const token = getToken();

    try {
        const queryParams = new URLSearchParams(data).toString();
        const response = await fetch(`${apiUrl}${endpoint}?${queryParams}`, {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            },
        });

        if (!response.ok) {
            if (response.status == 401) {
                userStore.update(store => {
                    return {
                      ...store,
                      isLoggedIn: false,
                      id: 0,
                      token: '',
                    };
                  });
            }
            throw new Error(`Error: ${response.status}`);
        }

        const count = response.headers.get('X-Count');
        const jsonData = await response.json();

        return {
            count: count,
            data: jsonData,
        };
    } catch (error) {
        console.error('Error in get request:', error);
        throw error;
    }
}
export async function post(endpoint: string, data: any) {
    const token = getToken();

    try {
        const response = await fetch(`${apiUrl}${endpoint}`, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        });

        if (!response.ok) {
            let result = await response.json();

            if (response.status == 401) { // 认证失败，清除用户信息
                if (result.message=="account error") {
                    result.message = "账户不存在"
                } else if (result.message=="username or password error") {
                    result.message = "账户或密码错误"
                }

                userStore.update(store => {
                    return {
                        ...store,
                        isLoggedIn: false,
                        id: 0,
                        token: '',
                    };
                });
            } else if (response.status == 400) {
                if (result.message=="plate number exist") {
                    result.message = "车牌号已存在"
                } else if (result.message=="vehicle present") {
                    result.message = "车辆已在库中"
                } else if (result.message=="vehicle not present") {
                    result.message = "车辆不在库中"
                }
            }

            throw new Error(`${result.message}`);
        }

        return await response.json();
    } catch (error) {
        console.error('Error in post request:', error);
        throw error;
    }
}
